package com.sumer.psychology.sharing.infrastructure.messaging.rabbitmq;

import com.sumer.psychology.common.notification.NotificationReader;
import com.sumer.psychology.common.port.adapter.messaging.Exchanges;
import com.sumer.psychology.common.port.adapter.messaging.rabbitmq.ExchangeListener;
import com.sumer.psychology.sharing.infrastructure.persistence.mongo.MongoSharedResourceRepository;
import org.apache.commons.lang3.StringUtils;

/**
 * 监听资源删除
 * <p/>
 * User: zhenguang.zhu
 * Date: 2014/11/3
 * Time: 15:15
 */
public class SharedResourceDeletedListener extends ExchangeListener {
    private MongoSharedResourceRepository mongoSharedResourceRepository;

    public SharedResourceDeletedListener(MongoSharedResourceRepository mongoSharedResourceRepository) {
        this.mongoSharedResourceRepository = mongoSharedResourceRepository;
    }

    @Override
    protected String exchangeName() {
        return Exchanges.DEFAULT_EXCHANGE_NAME;
    }

    @Override
    protected void filteredDispatch(String aType, String aTextMessage) {
        NotificationReader reader = new NotificationReader(aTextMessage);
        String sharedResourceId = reader.eventStringValue("sharedResourceId.identity");

        if (StringUtils.isNotBlank(sharedResourceId)) {
            mongoSharedResourceRepository().removeOne(sharedResourceId);
        }
    }

    @Override
    protected String[] listensTo() {
        return new String[]{"com.sumer.psychology.sharing.domain.model.SharedResourceDeletedEvent"};
    }

    public MongoSharedResourceRepository mongoSharedResourceRepository() {
        return mongoSharedResourceRepository;
    }
}
